package com.example.loginserver.controller;

import com.example.loginserver.utils.AesUtil;
import com.example.loginserver.utils.Result;
import com.oracle.tools.packager.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.encrypt.AesBytesEncryptor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@RestController
public class DownloadController {


    public static final String FILE_NAME = "/Users/luo/temp/example.txt";


    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {


        byte[] bytes = Files.readAllBytes(Paths.get(FILE_NAME));

//        String encrypt = AesUtil.encrypt(bytes, "MIGfMA0GCSqGSIb3");

//        AesBytesEncryptor aesBytesEncryptor = new AesBytesEncryptor("1234","4567");
//
//        byte[] encrypt = aesBytesEncryptor.encrypt(bytes);


        // 清空response，如果 reset，则相应的跨域的 header 也会被清空
//        response.reset();
        // 设置response的Header

        response.addHeader("Content-Disposition", "attachment;filename=" + FILE_NAME.substring(FILE_NAME.lastIndexOf("/") + 1));
        response.addHeader("Content-Length", "" + bytes.length);
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(bytes);
        toClient.flush();
        toClient.close();

    }

    /**
     * 服务器使用aes加密，浏览器解密
     * 下载加密过的内容
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/downloadEncryptedContent")
    public Result downloadEncryptedContent(HttpServletResponse response) throws Exception {


//        byte[] bytes = Files.readAllBytes(Paths.get(FILE_NAME));

        byte[] bytes = "我是被加密的字符串".getBytes(StandardCharsets.UTF_8);

        log.info("原始字节数组是：{}",bytes);

        String encrypt = AesUtil.encrypt(bytes, "MIGfMA0GCSqGSIb3");

        log.info("加密之后的字符串：{}", encrypt);

        return Result.OK(encrypt);

    }

}
